package com.xiaoy.core.base.security.login.action;

import java.util.Iterator;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.xiaoy.web.BasicAction;

@Namespace("/")
@Results({
	@Result(name = "login", location = "/workspace/index.do", type = "dispatcher") ,
	@Result(name = "logout", location = "/login.jsp", type = "dispatcher") ,})
public class LoginAction extends BasicAction{
	
	public String login () {
		
		try {
			String username = getParameter("username");
			String password = getParameter("password");
			System.out.println("u-p:"+username + "-" + password);
			Subject currentUser = SecurityUtils.getSubject();
			if (!currentUser.isAuthenticated() ) {
				UsernamePasswordToken token = new UsernamePasswordToken(username,password);
				token.setRememberMe(true);
				currentUser.login(token);
				Session session = currentUser.getSession();
				Iterator it = session.getAttributeKeys().iterator();
				while (it.hasNext()) {
					String key = it.next().toString();
					System.out.println(key+"-->"+session.getAttribute(key));;
				}
				session.setAttribute( "someKey", "aValue" );
				
				
			}
		}catch (Exception e) {
			
			setAttribute("msg", "");
			return "logout";
		}
		return "login";
	}
	
	
	public String logout () {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "logout";
	}
	
	
}


